#include "mymqtt.h"

//订阅
void sub(struct mg_connection *c, const char *fmt, ...)
{
    char buf[100];
    struct mg_mqtt_topic_expression te = {.topic = buf, .qos = 1};
    uint16_t sub_id = mgos_mqtt_get_packet_id();
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buf, sizeof(buf), fmt, ap);
    va_end(ap);
    mg_mqtt_subscribe(c, &te, 1, sub_id);
    LOG(LL_INFO, ("Subscribing to %s (id %u)", buf, sub_id));
}

//发布
void pub(struct mg_connection *c, const char *fmt, ...)
{
    char msg[200];
    struct json_out jmo = JSON_OUT_BUF(msg, sizeof(msg));
    va_list ap;
    int n;

    va_start(ap, fmt);
    n = json_vprintf(&jmo, fmt, ap);
    va_end(ap);

    mg_mqtt_publish(c, mgos_sys_config_get_mqtt_pub(), mgos_mqtt_get_packet_id(),
                    MG_MQTT_QOS(1), msg, n);
    //LOG(LL_INFO, ("%s -> %s", get_cfg()->mqtt.pub, msg));
    //printf("%s -> %s\n", get_cfg()->mqtt.pub, msg);
}

//事件处理
void evt_mqtt_handler(struct mg_connection *nc, int ev,
                      void *ev_data, void *user_data)
{
    struct mg_mqtt_message *msg = (struct mg_mqtt_message *)ev_data;

    if (ev == MG_EV_MQTT_CONNACK && nc != NULL)
    {
        sub(nc, "%s", "esp8266_E142CD/rpc/#");
    }
    else if (ev == MG_EV_MQTT_PUBLISH)
    {
        if (msg != NULL)
        {
            struct mg_str *s = &msg->payload;
            printf("receive:%s\n", s->p);
            mg_mqtt_puback(nc, msg->message_id);
        }
    }

    // free
    msg = NULL;

    (void)ev_data;
    (void)user_data;
}